﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;
using KingRoad.EPM.SafetyManagementBLL.UIRules;
using KingRoad.EPM.SafetyManagementEntity.Model;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    public class ScmSafeTrainingController : BaseController
    {
        //
        // GET: /ScmSafeTraining/

        /// <summary>
        /// 安全知识列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SafeTrainningList1(ScmSafetyknowledgeViewModel vm)
        {
            var type = "1";
            if (Request.Form["pageNum"] != null && Request.Form["pageNum"] != "")
            {
                ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            }
            else
            {
                ViewBag.pageNum = 1;
            }

            //每页多少条
            if (Request.Form["numPerPage"] != "" & Request.Form["numPerPage"] != null)
            {
                ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            }
            else
            {
                ViewBag.numPerPage = 20;
            }
            var typeId = PageType(type);
            var sqlStr = "";
            if (vm.TheSafetyKnowledge == null && vm.TheSafetyKnowledgeList == null)
            {
                sqlStr = " 1=1 AND Scd_ID='" + typeId + "'";
            }
            else
            {
                sqlStr = GetSearchSql(vm, typeId);
            }
            int totalRecord = 0;
            var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_CreateTime", out totalRecord, sqlStr);
            ViewBag.totalcount = totalRecord;
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafeTrainningList" + type, new ScmSafetyknowledgeViewModel
            {
                TheSafetyKnowledgeList = knowledgeList,
                TheSafetyKnowledge = vm.TheSafetyKnowledge,
                PublishBeginTime = vm.PublishBeginTime,
                PublishEndTime = vm.PublishEndTime,
            });

            //type = "1";
            //int totalRecord = 0;
            ////当前页码
            //ViewBag.pageNum = 1;
            ////每页多少条
            //ViewBag.numPerPage = 20;
            //var typeId = PageType(type);
            //var sqlContion = String.Format(" Scd_ID='{0}' ", typeId);
            //var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_TimeStamp", out totalRecord, sqlContion);
            //ViewBag.totalcount = totalRecord;
            //ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new ScmSafetyknowledgeViewModel { TheSafetyKnowledgeList = knowledgeList });
        }
        public ActionResult SafeTrainningList2(ScmSafetyknowledgeViewModel vm)
        {
           var type = "2";
           if (Request.Form["pageNum"]!=null&&Request.Form["pageNum"]!="")
           {
               ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
           }
           else
           {
               ViewBag.pageNum = 1;
           }
           
            //每页多少条
           if (Request.Form["numPerPage"]!=""&Request.Form["numPerPage"]!=null)
           {
               ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
           }
           else
           {
               ViewBag.numPerPage = 20;
           }
            var typeId = PageType(type);
            var sqlStr = "";
            if (vm.TheSafetyKnowledge==null&&vm.TheSafetyKnowledgeList==null)
            {
                 sqlStr = " 1=1 AND Scd_ID='" + typeId + "'";
            }
            else
            {
                 sqlStr = GetSearchSql(vm, typeId);
            }
            int totalRecord = 0;
            var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_CreateTime", out totalRecord, sqlStr);
            ViewBag.totalcount = totalRecord;
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafeTrainningList" + type, new ScmSafetyknowledgeViewModel
            {
                TheSafetyKnowledgeList = knowledgeList,
                TheSafetyKnowledge = vm.TheSafetyKnowledge,
                PublishBeginTime = vm.PublishBeginTime,
                PublishEndTime = vm.PublishEndTime,
            });


            //type = "2";
            //int totalRecord = 0;
            ////当前页码
            //ViewBag.pageNum = 1;
            ////每页多少条
            //ViewBag.numPerPage = 20;
            //var typeId = PageType(type);
            //var sqlContion = String.Format(" Scd_ID='{0}' ", typeId);
            //var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_TimeStamp", out totalRecord, sqlContion);
            //ViewBag.totalcount = totalRecord;
            //ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new ScmSafetyknowledgeViewModel { TheSafetyKnowledgeList = knowledgeList });
        }
        public ActionResult SafeTrainningList3(ScmSafetyknowledgeViewModel vm)
        {
            var type = "3";
            if (Request.Form["pageNum"] != null && Request.Form["pageNum"] != "")
            {
                ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            }
            else
            {
                ViewBag.pageNum = 1;
            }

            //每页多少条
            if (Request.Form["numPerPage"] != "" & Request.Form["numPerPage"] != null)
            {
                ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            }
            else
            {
                ViewBag.numPerPage = 20;
            }
            var typeId = PageType(type);
            var sqlStr = "";
            if (vm.TheSafetyKnowledge == null && vm.TheSafetyKnowledgeList == null)
            {
                sqlStr = " 1=1 AND Scd_ID='" + typeId + "'";
            }
            else
            {
                sqlStr = GetSearchSql(vm, typeId);
            }
            int totalRecord = 0;
            var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_CreateTime", out totalRecord, sqlStr);
            ViewBag.totalcount = totalRecord;
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafeTrainningList" + type, new ScmSafetyknowledgeViewModel
            {
                TheSafetyKnowledgeList = knowledgeList,
                TheSafetyKnowledge = vm.TheSafetyKnowledge,
                PublishBeginTime = vm.PublishBeginTime,
                PublishEndTime = vm.PublishEndTime,
            });

            //type = "3";
            //int totalRecord = 0;
            ////当前页码
            //ViewBag.pageNum = 1;
            ////每页多少条
            //ViewBag.numPerPage = 20;
            //var typeId = PageType(type);
            //var sqlContion = String.Format(" Scd_ID='{0}' ", typeId);
            //var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_TimeStamp", out totalRecord, sqlContion);
            //ViewBag.totalcount = totalRecord;
            //ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new ScmSafetyknowledgeViewModel { TheSafetyKnowledgeList = knowledgeList });
        }
        public ActionResult SafeTrainningList4(ScmSafetyknowledgeViewModel vm)
        {
            var type = "4";
            if (Request.Form["pageNum"] != null && Request.Form["pageNum"] != "")
            {
                ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            }
            else
            {
                ViewBag.pageNum = 1;
            }

            //每页多少条
            if (Request.Form["numPerPage"] != "" & Request.Form["numPerPage"] != null)
            {
                ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            }
            else
            {
                ViewBag.numPerPage = 20;
            }
            var typeId = PageType(type);
            var sqlStr = "";
            if (vm.TheSafetyKnowledge == null && vm.TheSafetyKnowledgeList == null)
            {
                sqlStr = " 1=1 AND Scd_ID='" + typeId + "'";
            }
            else
            {
                sqlStr = GetSearchSql(vm, typeId);
            }
            int totalRecord = 0;
            var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_CreateTime", out totalRecord, sqlStr);
            ViewBag.totalcount = totalRecord;
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafeTrainningList" + type, new ScmSafetyknowledgeViewModel
            {
                TheSafetyKnowledgeList = knowledgeList,
                TheSafetyKnowledge = vm.TheSafetyKnowledge,
                PublishBeginTime = vm.PublishBeginTime,
                PublishEndTime = vm.PublishEndTime,
            });

            //type = "4";
            //int totalRecord = 0;
            ////当前页码
            //ViewBag.pageNum = 1;
            ////每页多少条
            //ViewBag.numPerPage = 20;
            //var typeId = PageType(type);
            //var sqlContion = String.Format(" Scd_ID='{0}' ", typeId);
            //var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_TimeStamp", out totalRecord, sqlContion);
            //ViewBag.totalcount = totalRecord;
            //ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new ScmSafetyknowledgeViewModel { TheSafetyKnowledgeList = knowledgeList });
        }
        /// <summary>
        /// 安全知识列表—分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(ScmSafetyknowledgeViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
         
            var type = GetRequestFormValue<string>("pageType");
            var typeId = PageType(type);
            var sqlStr = GetSearchSql(vm, typeId);
            var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_TimeStamp", out totalRecord, sqlStr);
            ViewBag.totalcount = totalRecord;
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SafeTrainningList"+type, new ScmSafetyknowledgeViewModel
            {
                TheSafetyKnowledgeList = knowledgeList
            });
        }

        /// <summary>
        /// 安全知识列表—搜索
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SafeTrainningSearch(ScmSafetyknowledgeViewModel vm)
        {
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            //if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
            //    return SafeTrainningList("TurnoverList");
           
                var type = GetRequestFormValue<string>("pageType");
                var typeId = PageType(type);
                var sqlStr = GetSearchSql(vm, typeId);
                int totalRecord = 0;
                var knowledgeList = ScmSafetyknowledgeUIRule.GetSafetyknowledgeForSearch(ViewBag.pageNum, ViewBag.numPerPage, "Sk_CreateTime", out totalRecord, sqlStr);
                ViewBag.totalcount = totalRecord;
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
                return View("SafeTrainningList" + type, new ScmSafetyknowledgeViewModel
                {
                    TheSafetyKnowledgeList = knowledgeList,
                    TheSafetyKnowledge = vm.TheSafetyKnowledge,
                    PublishBeginTime = vm.PublishBeginTime,
                    PublishEndTime = vm.PublishEndTime,
                });
      
           
        }
        /// <summary>
        /// 安全知识查看
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(string id, string type)
        {
            PageType(type);
            var signle = ScmSafetyknowledgeUIRule.GetSafetyknowledgeById(id);
            var vm = new ScmSafetyknowledgeViewModel { TheSafetyKnowledge = signle };
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SafeKnowledge_Rules");//SafeKnowledge_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            return View(vm);
        }
        public ActionResult SkContent(string id)
        {
            var signle = ScmSafetyknowledgeUIRule.GetSafetyknowledgeById(id);
            var vm = new ScmSafetyknowledgeViewModel { TheSafetyKnowledge = signle };
            return View(vm);
        }
        /// <summary>
        /// 安全知识添加
        /// </summary>
        /// <returns></returns>
        /// 
      
        [ValidateInput(false)]
        public ActionResult SafeTrainningAdd(string type, string target, string skId)
        {

            PageType(type);
            ViewBag.OperationType = target;
            if (target == "add")
            {
                ScmSafetyknowledgeInfo signle = new ScmSafetyknowledgeInfo();
                signle.Sk_ID = Guid.NewGuid().ToString();
                signle.Sk_CreateTime = DateTime.Now;
                //TODO:当前登录人信息
                signle.Sk_PublishOrgID = GetLoginUserDepartmentId; //当前登录人所属机构id
                signle.Sk_PublishOrgName = GetLoginUserDepartmentName;//当前登录人所属机构名称
                signle.Sk_CreateUserID=GetLoginUserId;//当前登录人id
                signle.Sk_CreateName = GetLoginUserRealName;//当前登录人名
                //附件
                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(ScmSafetyknowledgeUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;
                var vm = new ScmSafetyknowledgeViewModel { TheSafetyKnowledge = signle };
                return View(vm);
            }
            else
            {
                var signle = ScmSafetyknowledgeUIRule.GetSafetyknowledgeById(skId);
                var vm = new ScmSafetyknowledgeViewModel { TheSafetyKnowledge = signle };
                //附件
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SafeKnowledge_Rules");//SafeKnowledge_Rules  BizType类型
                ViewBag.AssisId = signle.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
                return View(vm);
            }
        }
        
        [ValidateInput(false)]
        public JsonResult SafeTrainningAddHandle(ScmSafetyknowledgeViewModel vm)
        {
            if (vm == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "操作失败",
                    }
                };
            }

            dynamic jsonReturn = new ExpandoObject();
            string operation_str = string.Empty;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheSafetyKnowledge.Sk_UpdateUserID = GetLoginUserId;
                vm.TheSafetyKnowledge.Sk_ModifyName = GetLoginUserRealName;
                vm.TheSafetyKnowledge.Sk_UpdateTime = DateTime.Now;

                if (vm.OperationType == "add")
                {
                    operation_str = "添加";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.TheSafetyKnowledge.Assist_ID = AssistID;
                    vm.TheSafetyKnowledge.Scd_ID = PageType(vm.KnowledgeType);
                    ScmSafetyknowledgeUIRule.InsertEntity(vm.TheSafetyKnowledge);
                }
                if (vm.OperationType == "edit")
                {
                    operation_str = "更新";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.TheSafetyKnowledge.Assist_ID = AssistID;
                    vm.TheSafetyKnowledge.Scd_ID = PageType(vm.KnowledgeType);
                    ScmSafetyknowledgeUIRule.UpdateEntity(vm.TheSafetyKnowledge);
                }
            });
            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = string.Format("{0}成功", operation_str),
                    navTabId = GetTabId(vm.KnowledgeType),
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = string.Format("{0}失败",operation_str)
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        public string PageType(string type)
        {
            ViewBag.type = type;
            switch (type)
            {
                case "1":
                    ViewBag.typeName = "规章制度";
                    //获取模块ID
                    ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全规章制度);
                    //附件目录名
                    ViewBag.DirWhere = Models.DirName.安全规章制度;
                    return "F8338E01-25A8-4489-A1EC-A2238E490A8D";
                case "2":
                    ViewBag.typeName = "管理规范";
                    //获取模块ID
                    ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全管理规范);
                    //附件目录名
                    ViewBag.DirWhere = Models.DirName.安全管理规范;
                    return "83632D80-08D4-4539-85EA-5B32987A1921";
                case "3":
                    ViewBag.typeName = "管理文件";
                    //获取模块ID
                    ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全管理文件);
                    //附件目录名
                    ViewBag.DirWhere = Models.DirName.安全管理文件;
                    return "57403524-C919-46DD-B33B-3D93BB9A7198";
                case "4":
                    ViewBag.typeName = "安全培训";
                    //获取模块ID
                    ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.安全培训);
                    //附件目录名
                    ViewBag.DirWhere = Models.DirName.安全培训;
                    return "BBE406B3-88DF-4E8D-B3DF-88088D4AE001";
                default:
                    ViewBag.typeName = "安全知识";
                    //获取模块ID
                    ViewBag.MoudleID = 0;
                    //附件目录名
                    ViewBag.DirWhere = Models.DirName.安全知识;
                    return "8D96F223-2579-4628-B29B-40C9BC0F1C7A";
            }
        }

        public string GetTabId(string type)
        {
            string tabId = "";
            switch (type)
            {
                case "1":
                    tabId = "SafetyConstruction.ScmSafeTraining.SafeTrainningList1?type=1";
                    break;
                case "2":
                    tabId = "SafetyConstruction.ScmSafeTraining.SafeTrainningList2?type=2";
                    break;
                case "3":
                    tabId = "SafetyConstruction.ScmSafeTraining.SafeTrainningList3?type=3";
                    break;
                case "4":
                    tabId = "SafetyConstruction.ScmSafeTraining.SafeTrainningList4?type=4";
                    break;
                default:
                    break;
            }
            return tabId;
        }

        public string GetSearchSql(ScmSafetyknowledgeViewModel vm, string typeId)
        {
            var sqlStr = String.Format(" 1=1 AND Scd_ID='{0}' ", typeId);
            if (vm == null) return sqlStr;

            if (!String.IsNullOrEmpty(vm.TheSafetyKnowledge.Sk_Title))
                sqlStr += String.Format(" AND Sk_Title LIKE '%{0}%' ", vm.TheSafetyKnowledge.Sk_Title);
            if (!String.IsNullOrEmpty(vm.TheSafetyKnowledge.Sk_PublishOrgName))
                sqlStr += String.Format(" AND Sk_PublishOrgName LIKE '%{0}%' ", vm.TheSafetyKnowledge.Sk_PublishOrgName);
            if (!String.IsNullOrEmpty(vm.PublishBeginTime) && !String.IsNullOrEmpty(vm.PublishEndTime))
                sqlStr += String.Format(" AND Sk_CreateTime BETWEEN '{0}' AND '{1}' ", vm.PublishBeginTime, vm.PublishEndTime);
            if (!String.IsNullOrEmpty(vm.PublishBeginTime) && String.IsNullOrEmpty(vm.PublishEndTime))
                sqlStr += String.Format(" AND Sk_CreateTime BETWEEN '{0}' AND '{1}' ", vm.PublishBeginTime, DateTime.Now.ToString());
            if (!String.IsNullOrEmpty(vm.PublishEndTime) && String.IsNullOrEmpty(vm.PublishBeginTime))
                sqlStr += String.Format(" AND Sk_CreateTime BETWEEN '{0}' AND '{1}' ", "2000-02-05 14:17:06.763", vm.PublishEndTime);
            return sqlStr;
        }

        /// <summary>
        /// 安全知识-批量删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult SafeTrainningMultiDelete(string type,string ids)
        {
            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = ScmSafetyknowledgeUIRule.DeleteSafeTrainningMulti(ids);
            });

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = GetTabId(type),
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
    }
}
